package com.google.code.expr.lang;

import com.google.code.expr.runtime.EXPRRunTimeException;
import com.google.code.expr.runtime.EXPRRunTimeState;
import com.google.code.expr.runtime.EXPRUnknownVariableException;
import com.google.code.expr.runtime.EXPRValue;
import com.google.code.expr.runtime.EXPRVariable;



public class EXPRVariableRef extends EXPROperand {

	public String name;
	
	public EXPRVariableRef(String pName) {
		super();
		setName(pName);
	}
	
	public void setName(String pName) {
		if (pName!=null && pName.startsWith(VARIABLE)) {
			pName = pName.substring(1);
		}
		name = pName;
	}
	
	public String getName() {
		return name;
	}

	public String toString() {
		StringBuffer buffer = new StringBuffer();
		buffer.append(VARIABLE);
		buffer.append(name);
		return buffer.toString();
	}

	@Override
	public String resolveToString(EXPRRunTimeState pState) {
		EXPRVariable var = pState.getVariable(name);
		if (name!=null) {
			return var.resolveAsString();
		}
		return null;
	}

	@Override
	public EXPRValue resolveToValue(EXPRRunTimeState pState) throws EXPRRunTimeException {
		EXPRVariable var = pState.getVariable(name);
		if (var!=null) {
			return var.getValue();
		}
		else {
			throw new EXPRUnknownVariableException(this);
		}
	}
	
	
}
